# app.py 后端核心代码
from flask import Flask, render_template, jsonify
import sqlite3
from collections import defaultdict
import jieba
import re

app = Flask(__name__)

# 自定义情感词典（示例）
sentiment_words = {
    '好': 'positive', '不错': 'positive', '推荐': 'positive',
    '差': 'negative', '难吃': 'negative', '投诉': 'negative'
}

# 数据库连接
def get_db():
    conn = sqlite3.connect('reviews.db')
    conn.row_factory = sqlite3.Row
    return conn

# 情感分析函数
def analyze_sentiment(text):
    positive = negative = 0
    words = jieba.lcut(text)
    for word in words:
        if word in sentiment_words:
            if sentiment_words[word] == 'positive':
                positive += 1
            else:
                negative += 1
    if positive > negative:
        return 'positive'
    elif negative > positive:
        return 'negative'
    else:
        return 'neutral'

# 路由定义
@app.route('/')
def dashboard():
    #return "welcome to first page."
    return render_template('dashboard.html')

# 情感分布数据接口
@app.route('/api/sentiment')
def sentiment_data():
    conn = get_db()
    cursor = conn.cursor()

    cursor.execute('SELECT sentiment, COUNT(*) FROM reviews GROUP BY sentiment')
    data = {row[0]: row[1] for row in cursor.fetchall()}
    conn.close()
    #print("this is return result:" + jsonify(data))
    return jsonify(data)

# 评分分布接口
@app.route('/api/score_dist')
def score_dist():
    conn = get_db()
    cursor = conn.execute('''
        SELECT score, COUNT(*) as count
        FROM reviews
        GROUP BY score ORDER BY score
    ''')
    result = [{'score': row[0], 'count': row[1]} for row in cursor]
    conn.close()
    return jsonify(result)

# 分类统计接口
@app.route('/api/category_stats')
def category_stats():
    conn = get_db()
    cursor = conn.execute('''
        SELECT category, COUNT(*) as count, AVG(score) as avg_score
        FROM reviews
        GROUP BY category
    ''')
    result = [{
        'category': row[0],
        'count': row[1],
        'avg_score': round(row[2], 1)
    } for row in cursor]
    conn.close()
    return jsonify(result)

# 关键词提取接口
@app.route('/api/keywords/<type>')
def keywords(type):
    conn = get_db()
    cursor = conn.execute('SELECT content FROM reviews')
    texts = [row[0] for row in cursor.fetchall()]

    # 关键词提取逻辑
    keywords = []
    pattern = re.compile(r'服务|态度|热情' if type == 'service' else r'味道|口感|食材')
    for text in texts:
        words = jieba.lcut(text)
        keywords.extend([w for w in words if pattern.search(w)])

    # 统计词频
    freq = defaultdict(int)
    for word in keywords:
        freq[word] += 1
    return jsonify([{'name': k, 'value': v} for k, v in freq.items()])

if __name__ == '__main__':
    app.run(debug=True)